// +----------------------------
// | 上报成绩处理程序 20250717
// +----------------------------


// 1. 使用全局data8变量
const subjects = Object.keys(totalScore); //获取totalScore的key

// 使用data8.js中的教师数据：获取成字典数组
const teachers = teacher.reduce((acc, curr) => {
    acc[curr.班级] = curr;
    return acc;
}, {});

// 先统计每个班级的总人数（包括计分类别为0的学生）
const classTotalStudents = {};
data8.forEach(student => {
    const classNum = student.班级;
    if (!classTotalStudents[classNum]) {
        classTotalStudents[classNum] = 0;
    }
    classTotalStudents[classNum]++;
});

// 2. 筛选有效数据：把计分类别为0的去掉
function filterStudents(data) {
    // 在这里计算学生的总分，因为后面要用到
    return data.filter(student => student.计分类别 === 1 || student.计分类别 === 2)
        .map(student => {
            // 计算学生总分，只统计"计分学科"中包含的学科
            let totalScore = 0;
            // 将计分学科字符串拆分为数组
            const scoringSubjects = student.计分学科 ? student.计分学科.split(',') : [];
            
            // 遍历学生的计分学科
            scoringSubjects.forEach(subject => {
                // 检查该学科是否在subjects列表中且学生有该学科的分数（比较严谨）
                if (subjects.includes(subject) && typeof student[subject] === 'number') {
                    totalScore += student[subject];
                }
            });
            
            // 将总分添加到学生对象中
            return {
                ...student,
                总分: totalScore
            };
        });
}

const validStudents = filterStudents(data8);

// 3. 计算班级统计数据
function calculateClassStats(students) {
    const classStats = {};
    
    // 学生先按班级分组
    students.forEach(student => {
        const classNum = student.班级;
        if (!classStats[classNum]) {
            classStats[classNum] = {
                students: [],
                classTotalStudents: classTotalStudents[classNum] || 0, // 班级总人数（包括计分类别为0的学生）
                totalStudents: 0,     // 应考人数（计分类别为1或2的学生）
                recordStudents: 0,     // 计分人数（计分类别为2的学生）
                actualStudents: 0,    // 实考人数（总分>0的学生）
                totalScore: 0,        // 班级总分
                totalScoreAvg: 0,     // 班级总分平均分
                subjectScores: {}
            };
        }
        
        classStats[classNum].students.push(student);
    });
    
    // 计算每个班级的统计数据
    for (const classNum in classStats) {
        const classData = classStats[classNum];
        
        // 应考人数（列表中的人数）
        classData.totalStudents = classData.students.length;
        // 计分人数（计分类别为2的学生人数）
        classData.recordStudents = classData.students.filter(student => student.计分类别 === 2).length;

        // 实考人数（总分>0的人数）
        const actualStudents = classData.students.filter(student => {
            return student.总分 > 0;
        });
        classData.actualStudents = actualStudents.length;

        // 计算班级总分
        const totalScoreSum = classData.students.reduce((sum, student) => sum + student.总分, 0);
        classData.totalScore = totalScoreSum;
        classData.totalScoreAvg = classData.recordStudents > 0 ? 
            (totalScoreSum / classData.recordStudents).toFixed(2) : "0.00";
        
        // 初始化各科分数数组
        subjects.forEach(subject => {
            classData.subjectScores[subject] = [];
        });
        
        // 收集各科分数
        classData.students.forEach(student => {
            // 将计分学科字符串拆分为数组
            const scoringSubjects = student.计分学科 ? student.计分学科.split(',') : [];
            
            subjects.forEach(subject => {
                if (scoringSubjects.includes(subject)) {
                    // 保存学生的分数和计分类别
                    classData.subjectScores[subject].push({
                        score: student[subject],
                        category: student.计分类别
                    });
                }
            });
        });
    }
    
    return classStats;
}

// 获取班级统计数据
const classStats = calculateClassStats(validStudents);

// 4. 计算学科详细统计数据
function calculateSubjectDetails(scoreObjects, subject) {
    // 动态计算及格线(60%)、红分线(80%)和低分线(30%)
    const passScore = Math.round(totalScore[subject] * 0.6); //及格
    const excellentScore = Math.round(totalScore[subject] * 0.8); //高分
    const lowScore = Math.round(totalScore[subject] * 0.3); //低分

    // 过滤有效的成绩对象（分数>0）
    // const validScoreObjects = scoreObjects.filter(obj => obj.score > 0); //0分不统计
    const validScoreObjects = scoreObjects;
    
    if (validScoreObjects.length === 0) {
        return {
            subjectTotalScore: 0,
            avgScore: 0,
            passCount: 0,
            passRate: 0,
            excellentCount: 0,
            excellentRate: 0,
            lowCount: 0,
            lowRate: 0
        };
    }

    // 计算学科总分：所有学生的分数总和
    const subjectTotalScore = validScoreObjects.reduce((sum, obj) => sum + obj.score, 0);
    
    // 计算平均分：计分类别1和2的分数都计入总分，但只有类别2的计入人数
    const sumAll = subjectTotalScore;
    // 计入平均分的人数（类别2的人数）
    const countForAvg = validScoreObjects.filter(obj => obj.category === 2).length;
    
    // 如果没有计入平均分的人数，则平均分为0
    const avgScore = countForAvg > 0 ? sumAll / countForAvg : 0;
    
    // 只考虑计分类别为2的学生进行及格率、红分率和低分率的计算
    const category2ScoreObjects = validScoreObjects.filter(obj => obj.category === 2);
    const totalStudents = category2ScoreObjects.length;
    
    // 如果没有计分计人的学生，则各项统计为0
    if (totalStudents === 0) {
        return {
            subjectTotalScore: subjectTotalScore,
            avgScore: avgScore.toFixed(2),
            passCount: 0,
            passRate: 0,
            excellentCount: 0,
            excellentRate: 0,
            lowCount: 0,
            lowRate: 0
        };
    }
    
    const passCount = category2ScoreObjects.filter(obj => obj.score >= passScore).length;
    const excellentCount = category2ScoreObjects.filter(obj => obj.score >= excellentScore).length;
    const lowCount = category2ScoreObjects.filter(obj => obj.score <= lowScore).length;

    return {
        subjectTotalScore: subjectTotalScore,
        avgScore: avgScore.toFixed(2),
        passCount: passCount,
        passRate: totalStudents > 0 ? ((passCount / totalStudents) * 100).toFixed(2) : "0.00",
        excellentCount: excellentCount,
        excellentRate: totalStudents > 0 ? ((excellentCount / totalStudents) * 100).toFixed(2) : "0.00",
        lowCount: lowCount,
        lowRate: totalStudents > 0 ? ((lowCount / totalStudents) * 100).toFixed(2) : "0.00"
    };
}

// 5. 生成完整分析表格
function generateFullAnalysisTable(stats) {
    let table = '<h2>上报成绩统计表</h2>';
    table += '<table border="1"><tr>';
    
    // 表头
    table += '<th rowspan="2">班级</th>';
    table += '<th rowspan="2">班级人数</th>';
    table += '<th rowspan="2">应考人数</th>';
    table += '<th rowspan="2">计分人数</th>';
    table += '<th rowspan="2">实考人数</th>';
    table += '<th rowspan="2">总分</th>';
    table += '<th rowspan="2">总分平均分</th>';
    table += '<th rowspan="2">平均分排名</th>';
    table += '<th rowspan="2">班主任</th>';
    
    // 学科表头
    subjects.forEach(subject => {
        table += `<th colspan="10">${subject}</th>`;
    });
    
    table += '</tr><tr>';
    
    // 子表头
    subjects.forEach(() => {
        table += '<th>教师</th>';
        table += '<th>学科总分</th>';
        table += '<th>均分</th>';
        table += '<th>排名</th>';
        table += '<th>及格人数</th>';
        table += '<th>及格率%</th>';
        table += '<th>红分人数</th>';
        table += '<th>红分率%</th>';
        table += '<th>低分人数</th>';
        table += '<th>低分率%</th>';
    });
    
    table += '</tr>';
    
    // 计算所有班级的总分平均分用于排名
    const totalScoreAverages = [];
    for (const classNum in stats) {
        const avgScore = parseFloat(stats[classNum].totalScoreAvg);
        // 只有当平均分大于0时才加入排名
        if (avgScore > 0) {
            totalScoreAverages.push({
                classNum: classNum,
                avg: avgScore
            });
        }
    }
    
    // 按总分平均分降序排序
    totalScoreAverages.sort((a, b) => b.avg - a.avg);
    
    // 计算所有班级的各科均分用于排名
    const subjectAverages = {};
    subjects.forEach(subject => {
        subjectAverages[subject] = [];
        for (const classNum in stats) {
            const scoreObjects = stats[classNum].subjectScores[subject] || [];
            // 使用calculateSubjectDetails函数计算详细统计数据
            const details = calculateSubjectDetails(scoreObjects, subject);
            
            // 只有当平均分大于0时才加入排名
            if (parseFloat(details.avgScore) > 0) {
                subjectAverages[subject].push({
                    classNum: classNum,
                    avg: parseFloat(details.avgScore)
                });
            }
        }
        
        // 按均分降序排序
        subjectAverages[subject].sort((a, b) => b.avg - a.avg);
    });
    
    // 表格内容
    for (const classNum in stats) {
        const classData = stats[classNum];
        const classTeachers = teacher.find(t => t.班级 == classNum) || {};
        
        // 计算总分平均分排名
        const totalScoreRanking = totalScoreAverages.findIndex(item => 
            item.classNum == classNum) + 1;
        
        table += `<tr>`;
        table += `<td>${classNum}</td>`;
        table += `<td>${classData.classTotalStudents}</td>`;
        table += `<td>${classData.totalStudents}</td>`;
        table += `<td>${classData.recordStudents}</td>`;
        table += `<td>${classData.actualStudents}</td>`;
        table += `<td>${classData.totalScore.toFixed(2) || 0}</td>`;
        table += `<td>${classData.totalScoreAvg || '0.00'}</td>`;
        table += `<td>${totalScoreRanking || '-'}</td>`;
        table += `<td>${classTeachers.班主任 || ''}</td>`;
        
        // 各科数据
        subjects.forEach(subject => {
            const scoreObjects = classData.subjectScores[subject] || [];
            const details = calculateSubjectDetails(scoreObjects, subject);
            
            // 计算排名
            const ranking = subjectAverages[subject].findIndex(item => 
                item.classNum == classNum) + 1;
            
            table += `<td>${classTeachers[subject] || ''}</td>`;
            table += `<td>${details.subjectTotalScore}</td>`;
            table += `<td>${details.avgScore}</td>`;
            table += `<td>${ranking || '-'}</td>`;
            table += `<td>${details.passCount}</td>`;
            table += `<td>${details.passRate}</td>`;
            table += `<td>${details.excellentCount}</td>`;
            table += `<td>${details.excellentRate}</td>`;
            table += `<td>${details.lowCount}</td>`;
            table += `<td>${details.lowRate}</td>`;
        });
        
        table += `</tr>`;
    }
    
    table += '</table>';
    return table;
}

const tableHTML = generateFullAnalysisTable(classStats);


// +------------------------
// | 算奖分析
// +------------------------

if (suanJiang != undefined){
    // 请帮我计算算奖成绩，每个班获取前面多少人的平均成绩，做成表格，表头为“班级、班级人数、算奖人数、总分、总分平均分、算奖排名、各个学科的教师、算奖总分、算奖平均分、算奖排名”

    // 1. 计算每个班级的算奖统计数据
    function calculateAwardStats(students, classStats) {
        const awardStats = {};
        
        
        console.log(classStats);

        // 遍历每个班级
        for (const classNum in classStats) {
            // 获取该班级的学生（只考虑计分类别为2的学生）
            console.log("当前班级:", classNum, "类型:", typeof classNum);
            
            // 调试：检查学生数据的班级和计分类别
            const debugStudents = students.filter(student => student.班级 == classNum);
            console.log("该班级学生数:", debugStudents.length);
            console.log("该班级计分类别为2的学生数:", debugStudents.filter(s => s.计分类别 === 2).length);
            
            // 使用宽松比较(==)而不是严格比较(===)，以处理可能的类型不匹配
            const classStudents = students.filter(student => student.班级 == classNum && student.计分类别 === 2);
            
            console.log("筛选后的学生数:", classStudents.length);

            // 如果班级没有学生，跳过
            if (classStudents.length === 0) {
                continue;
            }
            
            // 按总分降序排序
            classStudents.sort((a, b) => b.总分 - a.总分);
            
            // 确定算奖人数（使用suanJiang中的配置，如果没有则默认取前3名）
            const awardCountObj = suanJiang.find(item => item.班级 == classNum);
            const awardCount = (awardCountObj && parseInt(awardCountObj.算奖人数)) || 3;
            // 确保算奖人数不超过实际学生数
            const actualAwardCount = Math.min(awardCount, classStudents.length);
            
            // 获取算奖学生
            const awardStudents = classStudents.slice(0, actualAwardCount);
            
            // 计算算奖总分
            const awardTotalScore = awardStudents.reduce((sum, student) => sum + student.总分, 0);
            // 计算算奖平均分
            const awardAvgScore = actualAwardCount > 0 ? (awardTotalScore / actualAwardCount).toFixed(2) : "0.00";
            
            // 初始化各科算奖分数
            const subjectAwardScores = {};
            subjects.forEach(subject => {
                subjectAwardScores[subject] = {
                    totalScore: 0,
                    avgScore: 0,
                    students: []
                };
            });

            console.log('算奖总分：'+awardTotalScore+"，各科算奖分数：",subjectAwardScores);
            
            // 计算各科算奖分数
            awardStudents.forEach(student => {
                // 将计分学科字符串拆分为数组
                const scoringSubjects = student.计分学科 ? student.计分学科.split(',') : [];
                
                // 遍历学生的计分学科
                scoringSubjects.forEach(subject => {
                    if (subjects.includes(subject) && typeof student[subject] === 'number') {
                        subjectAwardScores[subject].totalScore += student[subject];
                        subjectAwardScores[subject].students.push(student);
                    }
                });
            });
            
            // 计算各科算奖平均分
            subjects.forEach(subject => {
                const subjectStudentCount = subjectAwardScores[subject].students.length;
                if (subjectStudentCount > 0) {
                    subjectAwardScores[subject].avgScore = (subjectAwardScores[subject].totalScore / subjectStudentCount).toFixed(2);
                } else {
                    subjectAwardScores[subject].avgScore = "0.00";
                }
            });
            
            // 保存班级算奖统计数据
            awardStats[classNum] = {
                classTotalStudents: classStats[classNum].classTotalStudents,
                awardCount: actualAwardCount,
                totalScore: classStats[classNum].totalScore,
                totalScoreAvg: classStats[classNum].totalScoreAvg,
                awardTotalScore: awardTotalScore,
                awardAvgScore: awardAvgScore,
                subjectAwardScores: subjectAwardScores
            };
        }
        
        return awardStats;
    }
    
    // 2. 生成算奖分析表格
    function generateAwardAnalysisTable(awardStats) {
        let table = '<h2>算奖成绩分析表</h2>';
        table += '<table border="1"><tr>';
        
        // 表头
        table += '<th rowspan="2">班级</th>';
        table += '<th rowspan="2">班主任</th>';
        table += '<th rowspan="2">班级人数</th>';
        table += '<th rowspan="2">算奖人数</th>';
        // table += '<th rowspan="2">总分</th>';
        // table += '<th rowspan="2">总分平均分</th>';
        table += '<th rowspan="2">算奖总分</th>';
        table += '<th rowspan="2">算奖平均分</th>';
        table += '<th rowspan="2">算奖排名</th>';
        
        // 学科表头
        subjects.forEach(subject => {
            table += `<th colspan="4">${subject}</th>`;
        });
        
        table += '</tr><tr>';
        
        // 子表头
        subjects.forEach(() => {
            table += '<th>教师</th>';
            table += '<th>算奖总分</th>';
            table += '<th>算奖平均分</th>';
            table += '<th>算奖排名</th>';
        });
        
        table += '</tr>';
        
        // 计算所有班级的算奖平均分用于排名
        const awardAverages = [];
        for (const classNum in awardStats) {
            const avgScore = parseFloat(awardStats[classNum].awardAvgScore);
            // 只有当平均分大于0时才加入排名
            if (avgScore > 0) {
                awardAverages.push({
                    classNum: classNum,
                    avg: avgScore
                });
            }
        }
        
        // 按算奖平均分降序排序
        awardAverages.sort((a, b) => b.avg - a.avg);
        
        // 计算所有班级的各科算奖均分用于排名
        const subjectAwardAverages = {};
        subjects.forEach(subject => {
            subjectAwardAverages[subject] = [];
            for (const classNum in awardStats) {
                const avgScore = parseFloat(awardStats[classNum].subjectAwardScores[subject].avgScore);
                // 只有当平均分大于0时才加入排名
                if (avgScore > 0) {
                    subjectAwardAverages[subject].push({
                        classNum: classNum,
                        avg: avgScore
                    });
                }
            }
            
            // 按均分降序排序
            subjectAwardAverages[subject].sort((a, b) => b.avg - a.avg);
        });
        
        // 表格内容
        for (const classNum in awardStats) {
            const classData = awardStats[classNum];
            const classTeachers = teacher.find(t => t.班级 == classNum) || {};
            
            // 计算算奖平均分排名
            const awardRanking = awardAverages.findIndex(item => 
                item.classNum == classNum) + 1;
            
            table += `<tr>`;
            table += `<td>${classNum}</td>`;
            table += `<td>${classTeachers.班主任 || ''}</td>`;
            table += `<td>${classData.classTotalStudents}</td>`;
            table += `<td>${classData.awardCount}</td>`;
            // table += `<td>${classData.totalScore || 0}</td>`;
            // table += `<td>${classData.totalScoreAvg || '0.00'}</td>`;
            table += `<td>${classData.awardTotalScore.toFixed(2) || 0}</td>`;
            table += `<td>${classData.awardAvgScore || '0.00'}</td>`;
            table += `<td>${awardRanking || '-'}</td>`;
            
            // 各科数据
            subjects.forEach(subject => {
                const subjectData = classData.subjectAwardScores[subject];
                
                // 计算排名
                const ranking = subjectAwardAverages[subject].findIndex(item => 
                    item.classNum == classNum) + 1;
                
                table += `<td>${classTeachers[subject] || ''}</td>`;
                table += `<td>${subjectData.totalScore.toFixed(2) || 0}</td>`;
                table += `<td>${subjectData.avgScore || '0.00'}</td>`;
                table += `<td>${ranking || '-'}</td>`;
            });
            
            table += `</tr>`;
        }
        
        table += '</table>';
        return table;
    }
    
    // 3. 计算算奖统计数据
    const awardStats = calculateAwardStats(validStudents, classStats);

    console.log('算奖统计数据：', awardStats);
    
    // 4. 生成算奖分析表格
    const suanjiangHTML = generateAwardAnalysisTable(awardStats);

    document.getElementById('suanJiangResult').innerHTML = suanjiangHTML;
}